/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package diet.controller;

import diet.dao.DishDAO;
import diet.dao.DishDetailDAO;
import diet.dao.FoodDAO;
import diet.dto.DishDTO;
import diet.dto.DishDetailDTO;
import diet.dto.FoodDTO;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Vrety
 */
public class AddDishServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

//            String foodIDEss = request.getParameter("txtFoodIDEss");
//            String foodIDNon = request.getParameter("txtFoodIDNon");
//            Float ammount1 = Float.parseFloat(request.getParameter("txtAmount1"));
//            Float ammount2 = Float.parseFloat(request.getParameter("txtAmount2"));
            //Upload Image to server
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;

                items = upload.parseRequest(request);

                Iterator iter = items.iterator();
                Hashtable params = new Hashtable();
                String filename = null;
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        params.put(item.getFieldName(), item.getString());
                    } else {
                        try {
                            //upload to server
                            String itemName = item.getName();
                            filename = itemName.substring(
                                    itemName.lastIndexOf("\\") + 1);
                            String realPath = getServletContext().getRealPath("/")
                                    + "images/food\\" + filename;
                            File savedFile = new File(realPath);
                            item.write(savedFile);
                            //upload to source
                            // realPath = "E:\\Study\\FPT_Spring 2013\\XML\\Assignement Souce\\ass-xml\\DietPlanning\\web\\images\\dish" + filename;
                            //savedFile = new File(realPath);
                            //item.write(savedFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                //Get param and add to server
//                String dishName = request.getParameter("txtDishName");
//                String ImageURL = filename;
//                String Time = "Morning";
//                String Cooking = request.getParameter("txtCooking");
//
//
//                DishDTO dish = new DishDTO();
//                dish.setDishName(dishName);
//                dish.setImageURL(ImageURL);
//                dish.setTime(Time);
//                dish.setCalories(700);
//                dish.setStatus("Approval");
//                dish.setUserID(4);
//                //Add to DB
//                DishDAO dishdao = new DishDAO();
//                dishdao.add(dish);
//                // Add DishDetail to DB
//                DishDetailDAO dishDetailDao = new DishDetailDAO();
//                DishDetailDTO dishDetail = new DishDetailDTO();
//
//                dishDetail.setFoodID(Integer.parseInt(foodIDEss));
//                dishDetail.setAmmount(ammount1);
//                dishDetail.setEssential(true);
//                dishDetailDao.add(dishDetail);
//
//                dishDetail.setFoodID(Integer.parseInt(foodIDNon));
//                dishDetail.setAmmount(ammount2);
//                dishDetail.setEssential(false);
//                dishDetailDao.add(dishDetail);
                response.sendRedirect("addDish.jsp");

            }
        } catch (FileUploadException ex) {
            Logger.getLogger(AddDishServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
